﻿namespace ApiLib.Helpers;

/// <summary>
/// 
/// </summary>
public static class GlobalCache
{
    /// <summary>
    /// 
    /// </summary>
    private static readonly Dictionary<string, object> Caches = new();

    /// <summary>
    /// 包含key
    /// </summary>
    /// <param name="key"></param>
    public static bool HasKey(string key)
    {
        return Caches.ContainsKey(key);
    }
    
    /// <summary>
    /// 设置缓存
    /// </summary>
    /// <param name="key"></param>
    /// <param name="val"></param>
    public static void Set(string key, object val)
    {
        if (!string.IsNullOrEmpty(key))
        {
            Caches[key] = val;
        }
    }

    /// <summary>
    /// 获取缓存
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public static string? Get(string key)
    {
        if (Caches.TryGetValue(key, out var val))
        {
            return val as string;
        }

        return default;
    }

    /// <summary>
    /// 获取缓存
    /// </summary>
    /// <param name="key"></param>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static T? Get<T>(string key) where T : class
    {
        if (Caches.TryGetValue(key, out var val))
        {
            return val as T;
        }

        return default;
    }
}